package ru.st.selenium.applogic2;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import ru.st.selenium.applogic.FilmHelper;
import ru.st.selenium.model.Data;
import ru.st.selenium.model.Film;

public class FilmHelper2 extends DriverBasedHelper implements FilmHelper {

  public FilmHelper2(ApplicationManager2 manager) {
    super(manager.getWebDriver());
    this.manager = manager;
  }

  private ApplicationManager2 manager;

	@Override
	public void addFilm(Film film) {
		pages.filmPage
		  .clickAddMovieBtn();
		pages.filmPage
		  .setFilmTitle(film.getTitle())
		  .setFilmYear(film.getYear())
		  .clickSubmitBtn();
	}
	
	@Override
	public void deleteFilm(Film film) {
		pages.filmPage.clickFirstFilm();
		pages.filmPage.clickRemoveBtn();    
	}
	
	@Override
	public boolean isCreated() {
		return pages.filmPage.waitPageLoaded();
	}
	
	@Override
	public boolean isNotCreated() {
		return pages.addFilmPage.waitPageLoaded();
	}
	/*
	@Override
	public boolean isCreated(Film film) {
		manager.getNavigationHelper().openMainPage();		
		pages.internalPage.ensurePageLoaded();
		
		List<WebElement> films = driver.findElements(By.cssSelector("div.title"));

		for(WebElement filmElement: films) {
			String fTitle = filmElement.getText();
			if(fTitle.contains(film.getTitle())) {
				return true;
			}		
		}
		return false;
	}
	
	@Override
	public boolean isNotCreated(Film film) {
		manager.getNavigationHelper().openMainPage();
		List<WebElement> films = driver.findElements(By.cssSelector("div.title"));

		for(WebElement filmElement: films) {
			String fTitle = filmElement.getText();
			if(fTitle.contains(film.getTitle())) {
				return false;
			}	
		}
		return true;
	}
	*/

	@Override
	public List<Film> search(String title) {
		pages.internalPage.fillSearchField(title);
		Film film = new Film();
		List<Film> films = null;
		List<WebElement> elFilms = driver.findElements(By.cssSelector("div.title"));
	    for(WebElement filmElement: elFilms) {
	    	String fTitle = filmElement.getText();
			films.add(film.setTitle(fTitle));
		}
	    return films;
	}

	@Override
	public boolean filmsAreFound (String title) {
		pages.internalPage.fillSearchField(title);
		wait.until(presenceOfElementLocated(By.id("results")));
		List<WebElement> elFilms = driver.findElements(By.cssSelector("div.title"));
	    for(WebElement filmElement: elFilms) {
			String fTitle = filmElement.getText();
			if (fTitle.equals(title)) {
				return true;
			}
			else 
			    return false;						
		}
	    return false;
	}
	
	@Override
	public boolean nothingIsFound(String title) {
		pages.internalPage.fillSearchField(title);
		wait.until(presenceOfElementLocated(By.id("results")));
	    return(pages.filmPage.nothingFound());		
	}
	
}